package com.lanchetech.admin.config;

import com.alibaba.excel.util.CollectionUtils;
import com.lanchetech.admin.service.UserService;
import com.lanchetech.bean.vo.OrderSkuVO;
import com.lanchetech.common.enums.*;
import com.lanchetech.dao.*;
import com.lanchetech.entity.*;
import com.lanchetech.service.CommissionService;
import com.lanchetech.service.CommonOrderService;
import com.lanchetech.service.DaoService;
import com.lanchetech.service.FinanceService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Component
public class ScheduleTaskComp {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    OrdersMapper ordersMapper;

    @Autowired
    OrderSkuMapper orderSkuMapper;

    @Autowired
    CommentStatisticsMapper commentStatisticsMapper;

    @Autowired
    CommissionService commissionService;

    @Autowired
    UserCommissionMapper userCommissionMapper;

    @Autowired
    BargainActivityMapper bargainActivityMapper;

    @Autowired
    BargainSpuMapper bargainSpuMapper;

    @Autowired
    UserService userService;

    @Autowired
    FinanceService financeService;

    @Autowired
    DaoService daoService;

    @Autowired
    CommonOrderService commonOrderService;

    @Autowired
    PlatformCommissionRecordMapper platformCommissionRecordMapper;

    @Autowired
    IdentityMapper identityMapper;

    /**
     * 每天7时10分0秒执行，将7天前，快递订单，就已经发货的，已付款，未确认收货的，改为待评价，并添加默认5星好评
     */
//    @Scheduled(cron = "0 10 7 * * ?")
//    public void batchConfirmOrder() {
//        log.info("待评价定时任务开始执行！");
//        int count = 0;
//        Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.DATE, -7);
//
//        List<Orders> ordersList = ordersMapper.findAllByOrderTypeAndStatusAndLogisticsStatusAndCreatedAt(
//                OrderTypeEnum.ONLINE_EXPRESS.getType(),
//                OrdersStatusEnum.PAID.getStatus(),
//                calendar.getTime()
//        );
//
//        if (!CollectionUtils.isEmpty(ordersList)) {
//            ordersList.stream().forEach(orders -> commonOrderService.confirmOrder(orders));
//            count = ordersList.size();
//        }
//
//        log.info("待评价定时任务执行结束！已经处理{}条订单。", count);
//    }

    /**
     * 每天7时30分0秒执行，将14天前，待评价的，改为已完成
     */
//    @Scheduled(cron = "0 30 7 * * ?")
//    public void batchDoneOrder() {
//        log.info("已完成定时任务开始执行！");
//        Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.DATE, -14);
//
//        int count = ordersMapper.autoUpdateOrderStatus(OrdersStatusEnum.DONE.getStatus(), new Date(), OrdersStatusEnum.COMMENT.getStatus(), calendar.getTime());
//        orderSkuMapper.autoUpdateOrderSkuStatus(OrdersStatusEnum.DONE.getStatus(), OrdersStatusEnum.COMMENT.getStatus(), calendar.getTime());
//
//        log.info("已完成定时任务执行结束！已经处理{}条订单。", count);
//    }


    /**
     * 每天7时40分0秒执行，将冻结到期的，待发放的佣金发放给用户
     */
//    @Scheduled(cron = "0 40 7 * * ?")
//    public void batchIssueUserCommission() {
//        log.info("用户佣金发放定时任务开始执行！");
//        int count = 0;
//        List<UserCommission> userCommissionList = userCommissionMapper.findAllByStatusAndFreezeTime(UserCommissionStatusEnum.FREEZE.getStatus(), new Date());
//
//        if (!CollectionUtils.isEmpty(userCommissionList)) {
//            userCommissionList.stream().forEach(item -> {
//                // 发放佣金
//                commissionService.issueUserCommission(item);
//            });
//
//            count = userCommissionList.size();
//        }
//
//        log.info("用户佣金发放定时任务执行结束！已经处理{}条。", count);
//    }

    /**
     * 每天0点1分执行，将所有已经结束的砍价活动设置为已经关闭
     */
//    @Scheduled(cron = "0 1 0 * * ?")
//    public void batchCloseBargainActivity() {
//        log.info("将所有已经结束的砍价活动设置为已经关闭开始执行！");
//        int count = 0;
//        List<BargainActivity> list = bargainActivityMapper.findAllByEndTimeAndStatus(new Date(), ToggleEnum.ON.getStatus());
//
//        if (!list.isEmpty()) {
//            // 将所有的已过期的活动关闭
//            bargainActivityMapper.updateStatusByEndTimeAndStatus(ToggleEnum.OFF.getStatus(), new Date(), ToggleEnum.ON.getStatus());
//
//            // 将所有的已过期活动下的SPU关闭
//            bargainSpuMapper.updateStatusByActivityIds(ToggleEnum.OFF.getStatus(), list.stream().map(BargainActivity::getId).collect(Collectors.toList()));
//
//            count = list.size();
//        }
//        log.info("将所有已经结束的砍价活动设置为已经关闭定时任务执行结束！已经处理{}条。", count);
//    }

    /**
     * 每月8号10点执行，将所有上个月的合伙人平台分红统计出来并发放
     */
//    @Scheduled(cron = "0 0 10 8 * ?")
//    public void platformCommissionAutoIssue() {
//        // TODO:: 目前这钱就不发了！
//        log.info("发放平台分红-合伙人开始执行！");
//        Calendar c = Calendar.getInstance();
//        c.add(Calendar.MONTH, -1);
//        int lastMonthMaxDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
//        c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), 1, 0, 0, 0);
//        Date startTime = c.getTime();
//        c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), lastMonthMaxDay, 23, 59, 59);
//        Date endTime = c.getTime();
//
//        PlatformCommissionAmountVO vo = ordersMapper.sumPlatformCommissionAmountByTimeRange(startTime, endTime);
//        if (vo.getSumPayAmount() == null) {
//            vo.setSumPayAmount(BigDecimal.ZERO);
//        }
//        if (vo.getSumRefundAmount() == null) {
//            vo.setSumRefundAmount(BigDecimal.ZERO);
//        }
//
//
//        BigDecimal amount = vo.getSumPayAmount().subtract(vo.getSumRefundAmount()).multiply(daoService.getHipoConfigNumber(HipoConfigEnum.SHAREHOLDER_PLATFORM_COMMISSION_RATE.getConfig())).setScale(2, BigDecimal.ROUND_HALF_DOWN);
//
//        platformCommissionRecordMapper.insert(PlatformCommissionRecord.builder()
//                .payAmount(vo.getSumPayAmount())
//                .refundAmount(vo.getSumRefundAmount())
//                .amount(amount)
//                .type(PlatformCommissionTypeEnum.PARTNER.getType())
//                .createdAt(new Date())
//                .build());
//
//        if (amount.compareTo(BigDecimal.ZERO) > 0) {
//
//            // 获取所有的副总裁、总裁、董事（仅副总裁以上有业绩分红）
//            List<IdentitySimpleVO> identityList = identityMapper.findAllPartnerForDividends(new Date());
//            List<IdentitySimpleVO> identityListOverLevel34 = new ArrayList<>();
//            List<IdentitySimpleVO> identityListOverLevel4 = new ArrayList<>();
//
//            identityList.stream().forEach(i -> {
//                if (UserLevelEnum.PARTNER_L3.getLevel().equals(i.getPartnerLevel())) {
//                    identityListOverLevel34.add(i);
//                }
//                if (UserLevelEnum.PARTNER_L4.getLevel().equals(i.getPartnerLevel())) {
//                    identityListOverLevel34.add(i);
//                    identityListOverLevel4.add(i);
//                }
//            });
//
//            // 设置冻结时间
//            Calendar calendar = Calendar.getInstance();
//            calendar.add(Calendar.DATE, 7);
//            List<UserCommission> commissions = new ArrayList<>();
//            if (!identityList.isEmpty()) {
//                // 业绩分红
//                BigDecimal one = amount
//                        .multiply(new BigDecimal(0.4))
//                        .divide(new BigDecimal(identityList.size()), 2, BigDecimal.ROUND_HALF_UP)
//                        .setScale(2, BigDecimal.ROUND_HALF_UP);
//
//                BigDecimal two = identityListOverLevel34.isEmpty() ? BigDecimal.ZERO : amount
//                        .multiply(new BigDecimal(0.3))
//                        .divide(new BigDecimal(identityListOverLevel34.size()), 2, BigDecimal.ROUND_HALF_UP)
//                        .setScale(2, BigDecimal.ROUND_HALF_UP);
//
//
//                BigDecimal three = identityListOverLevel4.isEmpty() ? BigDecimal.ZERO : amount
//                        .multiply(new BigDecimal(0.3))
//                        .divide(new BigDecimal(identityListOverLevel4.size()), 2, BigDecimal.ROUND_HALF_UP)
//                        .setScale(2, BigDecimal.ROUND_HALF_UP);
//                identityList.stream().forEach(each -> {
//                    switch (UserLevelEnum.getByLevel(each.getPartnerLevel())) {
//                        case PARTNER_L2:
//                            commissions.add(build(each.getUserId(), JypConstant.HIPO_USER_ID, one, UserCommissionTypeEnum.PARTNER_L2_DIVIDENDS, calendar, amount, IdentityTypeEnum.PARTNER.getType(), null, "合伙人月平台分红"));
//                            break;
//                        case PARTNER_L3:
//                            commissions.add(build(each.getUserId(), JypConstant.HIPO_USER_ID, one.add(two), UserCommissionTypeEnum.PARTNER_L3_DIVIDENDS, calendar, amount, IdentityTypeEnum.PARTNER.getType(), null, "合伙人月平台分红"));
//                            break;
//                        case PARTNER_L4:
//                            commissions.add(build(each.getUserId(), JypConstant.HIPO_USER_ID, one.add(two).add(three), UserCommissionTypeEnum.PARTNER_L4_DIVIDENDS, calendar, amount, IdentityTypeEnum.PARTNER.getType(), null, "合伙人月平台分红"));
//                            break;
//                        default:
//                            break;
//                    }
//                });
//            }
//
//            if (!commissions.isEmpty()) {
//                userCommissionMapper.batchInsert(commissions);
//            }
//        }

//        log.info("发放平台分红-合伙人结束执行！");
//    }

//    private UserCommission build(Long superiorId, Long subordinateId, BigDecimal amount, UserCommissionTypeEnum typeEnum, Calendar calendar, BigDecimal performance, Byte identityType, Long orderSkuId, String remark) {
//        return UserCommission.builder()
//                .superiorId(superiorId)
//                .subordinateId(subordinateId)
//                .commission(amount)
//                .type(typeEnum.getType())
//                .freezeTime(calendar.getTime())
//                .status(UserCommissionStatusEnum.FREEZE.getStatus())
//                .createdAt(new Date())
//                .updatedAt(new Date())
//                .amount(performance)
//                .identityType(identityType)
//                .businessType(UserCommissionBusinessTypeEnum.USER.getType())
//                .orderSkuId(orderSkuId)
//                .remark(remark)
//                .build();
//    }

    /**
     * 每月1号早上9点，保存上月排行并发放奖励
     */
//    @Scheduled(cron = "0 0 9 1 * ?")
//    public void rewardLastMonthRank() {
//        log.info("保存上月排行榜，发放排行奖励开始执行");
////        userService.rankReward(RankTypeEnum.MONTH.getRankType());
//        log.info("保存上月排行榜，发放排行奖励结束执行");
//    }


    /**
     * 每月9号，下午3点，发放沉淀的分红
     */
//    @Scheduled(cron = "0 0 15 9 * ?")
//    public void rewardDividendPrecipitation() {
//        log.info("发放分红沉淀奖励开始执行");
//        commissionService.rewardDividendPrecipitation();
//        log.info("发放分红沉淀奖励结束执行");
//    }

    /**
     * 每周一下午3点，发放活动补贴
     */
//    @Scheduled(cron = "0 0 15 ? * Mon")
//    public void rewardMarketSubsidy() {
//        log.info("发放活动补贴奖励开始执行");
//        commissionService.rewardMarketSubsidy();
//        log.info("发放活动补贴奖励结束执行");
//    }

    /**
     * 每月1号下午2点30分发放联合创始人分红
     */
//    @Scheduled(cron = "0 30 14 1 * ?")
//    public void rewardDirectorCommission() {
//        log.info("发放联合创始人分红奖励开始执行");
//        commissionService.rewardDirectorCommission();
//        log.info("发放联合创始人分红奖励结束执行");
//    }

    /**
     * 每月9号，下午2点，发放分公司沉淀的分红
     */
//    @Scheduled(cron = "0 0 14 9 * ?")
//    public void rewardShareholderPrecipitation() {
//        log.info("发放分公司沉淀分红开始执行");
//        commissionService.rewardShareholderPrecipitation();
//        log.info("发放分公司沉淀分红结束执行");
//    }

    /**
     * 每天14点执行，平分释放福利补贴
     */
//    @Scheduled(cron = "0 0 14 * * ?")
//    public void rewardWelfare() {
//        log.info("平分释放福利补贴开始执行！");
//        commissionService.rewardWelfare();
//        log.info("平分释放福利补贴结束执行");
//    }

}
